<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>实时数据监控</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <!-- Chart.js 库 -->
    <style>
        .chart-container {
            width: 400px;
            height: 200px;
            margin: auto;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div id="div_chartSwitch" class="chart-container"><canvas id="chartSwitch"></canvas></div>
<div id="div_chartVoltage" class="chart-container"><canvas id="chartVoltage"></canvas></div>
<div id="div_chartPosition" class="chart-container"><canvas id="chartPosition"></canvas></div>
<div id="div_chartTemperature" class="chart-container"><canvas id="chartTemperature"></canvas></div>
<div id="div_chartAirPressure" class="chart-container"><canvas id="chartAirPressure"></canvas></div>
<div id="div_chartAltitude" class="chart-container"><canvas id="chartAltitude"></canvas></div>

<script>
    const updateInterval = 1000; // 更新间隔，单位为毫秒（1秒）

    let chartSwitch, chartVoltage, chartPosition, chartTemperature, chartAirPressure, chartAltitude;

    function generateMockData(length = 10) {
        return Array.from({ length }, () => ({
            value: null, 
            timestamp: new Date().toLocaleTimeString()
        }));
    }

    function drawChart(canvasId, data, label, color) {
		const elem = document.getElementById(canvasId)
		const ctx = elem.getContext('2d');

        return new Chart(ctx, {
            type: 'line',
            data: {
                labels: data.map(entry => entry.timestamp),
                datasets: [{
                    label: label,
                    data: data.map(entry => entry.value),
                    borderColor: color,
                    backgroundColor: `rgba(${color.slice(1).split('').join(',')}, 0.2)`
                }]
            },
            options: {
                animation: {
                    duration: 0
                },
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    function updateData(chart, newData) {
        chart.data.labels.shift();
        chart.data.labels.push(newData.timestamp);
        chart.data.datasets.forEach((dataset) => {
            dataset.data.shift();
            dataset.data.push(newData.value);
        });
        chart.update();
    }

    function fetchDataAndDrawCharts() {
        // 生成初始模拟数据
		const mockSwitchData = generateMockData(60);
        const mockVoltageData = generateMockData(60); // 生成60个数据点用于开始
		const mockPositionData = generateMockData(60);
        const mockTemperatureData = generateMockData(60);
        const mockAirPressureData = generateMockData(60);
        const mockAltitudeData = generateMockData(60);

        // 绘制初始图表
		chartSwitch = drawChart('chartSwitch', mockSwitchData, '开关', 'rgba(255, 30, 30, 1)');
        chartVoltage = drawChart('chartVoltage', mockVoltageData, '电压 (V)', 'rgba(76, 99, 132, 1)');
		chartPosition = drawChart('chartPosition', mockPositionData, '编码器位置', 'rgba(88, 55, 100, 1)');
        chartTemperature = drawChart('chartTemperature', mockTemperatureData, '温度 (℃)', 'rgba(54, 162, 235, 1)');
        chartAirPressure = drawChart('chartAirPressure', mockAirPressureData, '气压(Pa)', 'rgba(255, 206, 86, 1)');
        chartAltitude = drawChart('chartAltitude', mockAltitudeData, '海拔高度 (m)', 'rgba(75, 192, 192, 1)');

        // 设置定时器，每秒更新图表数据
        setInterval(() => {
            fetch("/getdata")
                .then(response => response.json())
                .then(data => {
					date = new Date().toLocaleTimeString()
					updateData(chartSwitch, { value: data.switch, timestamp:  date});
					updateData(chartVoltage, { value: data.voltage, timestamp:  date});
					updateData(chartPosition, { value: data.position, timestamp:  date});
					updateData(chartTemperature, { value: data.temperature, timestamp: date });
					updateData(chartAirPressure, { value: data.pressure, timestamp: date });
					updateData(chartAltitude, { value: data.altitude, timestamp: date });
                })
                .catch(error => console.error("获取数据失败：", error));
        }, updateInterval);
    }

    // 将 fetchDataAndDrawCharts 放入 window.onload 中，确保在页面加载完成后执行
    window.onload = function() {
        fetchDataAndDrawCharts();
    };
</script>

</body>
</html>